define(function(require, exports, module) {
  var $ = require("$");
  var bootbox = require("bootbox");
  var dtUtil = require('datatableutil');
  require("bootstrap_commonrequire");
  var nav = require("bootstrap_nav");
  var loader = require("./loader/loader");
  require("moment");
  require('daterangepicker.css');
  require('bootstrap-daterangepicker');
  require('select2.css');
  require('select2');

  exports.init = function(param) {

    $(document).ready(function() {
      // 蒙版
      loader.loading("数据加载中，请稍后……");
      var myId = -1;
      // 存储按照查询条件查询出来的所有记录的id和sessios_id
      var my_sessions_ids = new Array();
      // 获取当前页面的json数据
      var alldata={};
      
      // 加载自定义模板-条件区域
      var template = require("./phonebillexception.tpl");
      var Widget = require("widget");
      var Component = Widget.extend({
        template : template
      });
      new Component({
        renderTo : "queryAreaId"
      });
      
      var startIndex;
      
      var state = [ {
        "id" : "untreated",
        "text" : "未处理"
      }, {
        "id" : "processed",
        "text" : "处理成功"
      }, {
        "id" : "exception",
        "text" : "处理失败"
      } ];
      $('#handleState').select2({
        placeholder : "处理状态",
        allowClear : true,
        data : state
      });
      
      var ability = [ {
        "id" : "TalksV2",
        "text" : "IMS多方通话"
      }, {
        "id" : "ScheduleConference",
        "text" : "专业会议"
      }, {
        "id" : "EcpMeet",
        "text" : "ECP多方通话"
      }, {
        "id" : "EcpDial",
        "text" : "ECP点击拨号"
      }, {
        "id" : "Dial",
        "text" : "IMS点击拨号"
      }, {
        "id" : "VoiceNotice3",
        "text" : "IMS文字语音短信"
      }, {
        "id" : "AudeoSend",
        "text" : "IMS语音留言"
      }, {
        "id" : " ",// 此处有空格
        "text" : "空"
      } ];
      $('#abilityType').select2({
        placeholder : "能力类型",
        allowClear : true,
        data : ability
      });
      
      // 获取隐藏域中的查询条件
      var _start = localStorage.getItem("_start");
      // 清空缓存中的信息
      localStorage.setItem("_start","");
      
      function getCondition() {
        //获取查询条件
        var handleState = $('#handleState').val();// 处理状态
        var callIdentifier = $('#callIdentifier').val();// 处理状态
        var abilityType = $('#abilityType').val();// 能力类型
        var queryStr = "";

        if (handleState != '' && handleState != null) {
          queryStr += ("tmiu.process_state ='" + handleState + "';");
        }
        if (callIdentifier != '' && callIdentifier != null) {
          queryStr += ("tmiu.call_identifier like '%" + callIdentifier + "%';");
        }
        if (abilityType != '' && abilityType != null) {
          queryStr += ("tmiu.ability_type ='" + abilityType + "';");
        }
        
        var daterange = daterangeCom.getPickerRange();
        if (daterange) {
          var daterange = daterange.split("/");
          // 只获取起始或截止的那一天的时间，这样可以确保是一天
          var startTime = daterange[0];
          var endTime = daterange[1];
          queryStr += ("tmiu.create_time BETWEEN '" + startTime + " 00:00:00' AND '" + endTime + " 23:59:59'" + ";");
        }
        
        return queryStr;
      }
      
      // 初始化日期范围选择控件
      var DateRange = require('daterangeinput');
      var daterangeAttrs = {
        daterangeId : "querydatewrapper_rang",
        label : "日期"
      };
      var daterangeCom = new DateRange({
        attrs : daterangeAttrs,
        renderTo : 'querydatewrapper'
      });
      daterangeCom.setRangeToToday();
      
      //加载表单模板和数据
      var Table = require("table");
      // 查询内容显示
      new Table({
        attrs : {
          id : "data_table",
          isHovered : false,
          isStriped : true,
          isBordered : false
        },
        renderTo : param.divWrapperId
      });
      
      // 信息显示
      var accountinfo_data_table = $('#data_table').dataTable({
        "sDom" : "<'hidden'<'span6'l><'hidden'f>r>t<'row-fluid'<'span6'i><'span6'p>>",
        "bJQueryUI" : false,
        "oLanguage" : {
          "sUrl" : "/business/js/common/table/src/lang/dataTable.cn.txt"
        },
        "sPaginationType" : "bootstrap", // 分页自带两种样式，full_numbers和two_button(默认)
        'bPaginate' : true, // 是否分页
        "bProcessing" : true, // 当datatable获取数据时候是否显示正在处理提示信息。
        "bServerSide" : true, // 指定服务器端分页
        "bDeferRender" : true,
        "bFilter" : true,
        "bSort" : true,
        "bInfo" : true,
        "sAjaxSource" : param.ajaxUrl,
        "iDisplayLength" : DATATABLES_CONFIG.iDisplayLength.DEFAULT, // 默认分页的每页记录数
        "fnServerData" : function(sSource, aoData, fnCallback, oSettings) {
          var queryparam = dtUtil.convert_aoData(aoData);

          startIndex = queryparam.start;
          if(_start != null && _start!=''){
            queryparam.start = _start;
            _start = null;
          }
          
          //拼接where查询条件
          var cond = getCondition();
          if (cond != '' && cond != null) {
            queryparam.q += cond;
          }

          // 添加自己的额外参数
          oSettings.jqXHR = $.ajax({
            "dataType" : 'json',
            "contentType" : "application/json;charset=UTF-8",
            "type" : "GET",
            "url" : sSource,
            "data" : queryparam, // 将请求数据转换为后台要求的JSON格式
            "success" : function(json) {
              if (json.flag == '000000') {
                // 隐藏蒙版
                loader.noloading();
                dtUtil.successCallback(json, aoData, fnCallback);
                // 获取当前页面的json数据
                alldata = json;
              } else {
                oauth2Relogin();
              }
            }
          });

        },
        "aoColumns" : [ {
          "sTitle" : "id",
          "bSortable" : false,
          "mData" : "id",
          "bVisible" : false,
          "mRender" : function(data, type, full) {
            myId=data;
            return myId;
          }
        }, {
          "sTitle" : "ims_id",
          "bSortable" : false,
          "mData" : "ims_id",
          "bVisible" : false
        }, {
          "sTitle" : "user_id",
          "bSortable" : false,
          "mData" : "user_id",
          "bVisible" : false
        }, {
          "sTitle" : "会话标识",
          "bSortable" : false,
          "mData" : "session_id",
          "mRender" : function(data, type, full) {
            var ret = '<div>';
            ret += '<a href="javascript:void(0);" class="btn-link" title="查看详情">'+data.substr(0,18)+'...</a>';
            return ret += '</div>';
          }
        }, 
        {
          "sTitle" : "应用标识",
          "bSortable" : false,
          "mData" : "app_key",
          "bVisible" : false
        }, {
          "sTitle" : "账号标识",
          "bSortable" : false,
          "mData" : "cust_account",
          "bVisible" : false
        }, {
          "sTitle" : "主叫号码",
          "bSortable" : false,
          "mData" : "caller"
        }, {
          "sTitle" : "被叫号码",
          "bSortable" : false,
          "mData" : "phones",
          "mRender" : function(data, type, full) {
            var ret = '<div title="' + data + '">';
            if(data.length <= 20){
//              ret += '<a href="javascript:void(0);" class="btn-link-1">' + data + '</a>';
              ret += "<div class='myphones'>" + data + "</div>";
            }else{
//              ret += '<a href="javascript:void(0);" class="btn-link-1">' + data.substr(0,20) + '...</a>';
              ret += "<div class='myphones'>" + data.substr(0,15) + "...</div>";
            }
            return ret += '</div>';
          }
        }, {
          "sTitle" : "创建时间",
          "bSortable" : false,
          "mData" : "create_time"
        }, {
          "sTitle" : "时长",
          "bSortable" : false,
          "mData" : "duration",
          "bVisible" : false
        }, {
          "sTitle" : "会议状态",// 其实没用
          "bSortable" : false,
          "mData" : "status",
          "bVisible" : false
        }, {
          "sTitle" : "通话次数",
          "bSortable" : false,
          "mData" : "total_amount",
          "bVisible" : false
        }, {
          "sTitle" : "计费号码",
          "bSortable" : false,
          "mData" : "chargeNumber",
          "bVisible" : false
        }, {
          "sTitle" : "是否接收完话单",
          "bSortable" : false,
          "mData" : "isAccepted",
          "bVisible" : false,
          "mRender" : function(data, type, full) {
            if (data == "0")
              return "未接收完";
            else if (data == "1")
              return "已接收完";
            else
              return "未知";
          }
        }, {
          "sTitle" : "能力类型",
          "bSortable" : false,
          "mData" : "ability_type",
//          "bVisible" : false,
          "mRender" : function(data, type, full) {
            if (data == "TalksV2")
              return "IMS多方通话";
            else if (data == "ScheduleConference")
              return "专业会议";
            else if (data == "EcpMeet")
              return "ECP多方通话";
            else if (data == "Dial")
              return "IMS点击拨号";
            else if (data == "EcpDial")
              return "ECP点击拨号";
            else if (data == "VoiceNotice3")
              return "IMS文字语音短信";
            else if (data == "AudeoSend")
              return "IMS语音留言";
            else if (data == "")
              return "空";
            else
              return "未知";
          }
        }, {
          "sTitle" : "处理状态",
          "bSortable" : false,
          "mData" : "process_state",
          "mRender" : function(data, type, full) {
            if (data == "processed")
//              return "处理成功";
              return "<div class='fontcir' style='font-size:160%;color:green;margin-left:20px;' title='处理成功'><b>✔</b></div>";
            else if (data == "untreated")
//              return "未处理";
              return "<div class='fontcir' style='font-size:160%;color:#ffa500;margin-left:20px;' title='未处理'><b>?</b></div>";
            else if (data == "exception")
//            return "处理失败";
              return "<div class='fontcir' style='font-size:160%;color:red;margin-left:20px;' title='处理失败'><b>×</b></div>";
            else
              return "未知";
          }
        }, {
          "sTitle" : "备注",
          "bSortable" : false,
          "mData" : "comments",
          "bVisible" : false
        }, {
          "sTitle" : "应有数",
          "bSortable" : false,
          "mData" : "tccount",
          "bVisible" : false
        }, {
          "sTitle" : "实际数",
          "bSortable" : false,
          "mData" : "tmicount",
          "bVisible" : false
        }, {
          "sTitle" : "soap_sessionid",
          "bSortable" : false,
          "mData" : "soap_sessionid",
          "bVisible" : false
        }, {
          "sTitle" : "操作",
          "bSortable" : false,
          "mData" : "comments",
          "mRender" : function(data, status, full) {
            var ret = '<div class="btn-group" style="margin-top: 8px;">';
            // 需要修改下按钮位置处的图标
            ret += '<a href="javascript:void(0);" class="btn icon-refresh contrast" title="手动同步"></a>';
            return ret += '</div>';
          }
        } ],
        "fnDrawCallback" : function(oSettings) {
          // 表格绘制完成后，去除width属性，使表格可缩放
          $('#' + oSettings.sTableId).css("width", "");
        }
      });

      
      // 查询按钮
      $('#querybtn').click(function() {
        //蒙版
        loader.loading("数据加载中，请稍后……");
        accountinfo_data_table.fnFilter("");
        return false;
      });
      
      // 一键同步按钮
      $('#synchrobtn').click(function() {
        var bool = window.confirm("您确定要将以下异常话单全部同步吗?");
        if(bool){
          // JSON字符串转换为JSON对象
          var data = eval(alldata.data);
          var mylen = data.items.length;
          
          // 判断items中的数据，若存在则继续执行
          if(mylen > 0){
            loader.loading("正在一键同步中，请稍后……");

            //拼接where查询条件
            var cond = getCondition();
            // 将数据提交到后台
            $.ajax({
              url : "/unusual/synchroAll.do",
              dataType : "json",
              data : "q=" + cond,
              type : "POST",
              async : true,
              success : function(json) {
                if (json.flag == '000000') {
                  // 刷新表单
                  accountinfo_data_table.fnFilter("");
                  loader.noloading();
                } else {
                  oauth2Relogin();
                }
              },
              error : function() {
                loader.noloading();
                bootbox.alertTimeout("网络请求失败，请重试！");
              }
            });
          }
        }
        
        return false;
      });
      
      
      // 获取当前时间，用来默认设置年月
      var myDate = new Date();
      var nowYear = myDate.getFullYear();
      var nowMonth = myDate.getMonth() + 1;
      if(nowMonth < 10){
        nowMonth = "0" + nowMonth;
      }
      
      // 抓取数据按钮
      $('#grabdatabtn').click(function() {
        // 显示蒙版
        ruleinfo(' ');//暂未设置
        
        // 抓取数据蒙版，“抓取年”下拉菜单
        var myYear = [ {"id" : "2014","text" : "2014"}, 
                       {"id" : "2015","text" : "2015"}, 
                       {"id" : "2016","text" : "2016"}, 
                       {"id" : "2017","text" : "2017"}, 
                       {"id" : "2018","text" : "2018"} ];
        $('#grabyear').select2({
          placeholder : "抓取年",
          allowClear : true,
          data : myYear
        });
        $('#grabyear').select2('val',nowYear);// 默认是当前年份
        
        // 抓取数据蒙版，“抓取月”下拉菜单
        var myMonth = [ {"id" : "01","text" : "1月"}, 
                        {"id" : "02","text" : "2月"}, 
                        {"id" : "03","text" : "3月"},
                        {"id" : "04","text" : "4月"}, 
                        {"id" : "05","text" : "5月"}, 
                        {"id" : "06","text" : "6月"},
                        {"id" : "07","text" : "7月"}, 
                        {"id" : "08","text" : "8月"}, 
                        {"id" : "09","text" : "9月"},
                        {"id" : "10","text" : "10月"}, 
                        {"id" : "11","text" : "11月"}, 
                        {"id" : "12","text" : "12月"},
                        {"id" : "-1","text" : "全部"} ];// 所有月份的统计，在action中设置了条件
        
        $('#grabmonth').select2({
          placeholder : "抓取月",
          allowClear : true,
          data : myMonth
        });
        $('#grabmonth').select2('val',nowMonth);// 默认是当前月份
        
        
        // 抓取数据蒙版，返回按钮事件
        $("#btndialogcancel").click(function(event) {
          loader.noloading();
          // 蒙版消失
          $('#my_phonebill_id').modal('hide');
        });
        
        
        // 蒙版中，抓取数据按钮事件
        $("#grabdataconfirm").click(function() {
          // 获取下拉菜单中的信息
          var myYear = $("#grabyear").val();
          var myMonth = $("#grabmonth").val();
          if(myYear.length == 0 || myMonth.length == 0){
            $('#my_time').show();// 显示“请选择时间”的提示
          }else {
            loader.loading("数据加载中，请稍后……");
            $('#my_time').hide();// 隐藏“请选择时间”的提示
            $('#my_phonebill_id').modal('hide');// 隐藏模态框
            
            var formdata2= {
                grabYear : myYear,
                grabMonth : myMonth
            };
            // 将数据提交到后台
            $.ajax({
              url : "/unusual/queryAndInsertUnusual.do",
              dataType : "json",
              data : "data=" + JSON.stringify(formdata2),
              type : "POST",
              async : true,
              success : function(json) {
                if (json.flag == '000000') {
//                  nav.toPageView("pub/phonebillexception.html");
                  loader.noloading();
                  // 蒙版消失
                  $('#my_phonebill_id').modal('hide');
                  return true;
                } else {
                  oauth2Relogin();
                }
              },
              error : function() {
                loader.noloading();
                bootbox.alertTimeout("网络请求失败，请重试！");
              }
            });
          }
          
        });
        
        return false;
      });
      
      
      // 蒙版显示
      var ruleinfo = function(context) {
//        loader.loading("数据加载中，请稍后……");
        var ruleinfo_init = require("./phonebillexceptionmodal");
        if ($("#phonebill_id").length <= 0)
          $("body").append("<div id='phonebill_id'></div>");
        ruleinfo_init.init({
              "title" : "请选择需要抓取的时间",
              "renderTo" : "phonebill_id",
              "details": context
        });
      };
      
      
      // 操作，手动同步按钮
      $("#data_table tbody").on("click", "tr>td>div>a.icon-refresh", function(e) {
        var rowNode = this.parentNode.parentNode.parentNode;
        var rowData = accountinfo_data_table.fnGetData(rowNode);
        
        var formdata3= {
            id : rowData.id,
            session_id : rowData.session_id
        };
        // 将数据提交到后台
        $.ajax({
          url : "/unusual/synchroHanded.do",
          dataType : "json",
          data : "data=" + JSON.stringify(formdata3),
          type : "POST",
          async : false,
          success : function(json) {
            if (json.flag == '000000') {
              loader.noloading();
            } else {
              oauth2Relogin();
            }
          },
          error : function() {
            loader.noloading();
            bootbox.alertTimeout("网络请求失败，请重试！");
          }
        });
        
        // 刷新表单
        accountinfo_data_table.fnFilter("");
        return false;
      });
      
      
      // 查看详情
      $("#data_table tbody").on("click", "tr>td>div>a.btn-link", function(e) {
        var rowNode = this.parentNode.parentNode.parentNode;
        var rowData = accountinfo_data_table.fnGetData(rowNode);
        
        // 能力类型
        var ability_type = rowData.ability_type;
        if(ability_type == "TalksV2"){
          ability_type = "IMS多方通话";
        }else if (ability_type == "ScheduleConference"){
            ability_type = "专业会议";
        }else if (ability_type == "EcpMeet"){
            ability_type = "ECP多方通话";
        }else if(ability_type == "EcpDial"){
            ability_type = "ECP点击拨号";
        }else if(ability_type == "Dial"){
            ability_type = "IMS点击拨号";
        }else if (ability_type == "VoiceNotice3"){
            ability_type = "IMS文字语音短信";
        }else if (ability_type == "AudeoSend"){
            ability_type = "IMS语音留言";
        }else if (ability_type == ""){
            ability_type = "空";
        }else{
            ability_type = "未知";
        }
        
        // 处理状态
        var process_state = rowData.process_state;
        if(process_state == "processed"){
          process_state = "处理成功";
        }else if(process_state == "untreated"){
          process_state = "未处理";
        }else if (process_state == "exception"){
          process_state = "处理失败";
        }else{
          process_state = "未知";
        }
        
        // 处理状态
        var isAccepted = rowData.isAccepted;
        if(isAccepted == "0"){
          isAccepted = "未接收完";
        }else if(isAccepted == "1"){
          isAccepted = "已接收完";
        }else{
          isAccepted = "未知";
        }
        
        // 查看详情
        numPoolDetail("会话标识：" + rowData.call_identifier + ",,"
                    + "账号标识：" + rowData.identifier + ",,"
                    + "主叫号码：" + rowData.caller + ",,"
                    + "被叫号码：" + rowData.phones + ",,"
                    + "创建时间：" + rowData.create_time + ",,"
                    + "时长：" + rowData.duration + "分钟,,"
//                    + "会议状态：" + rowData.status + ",,"
                    + "单价：" + rowData.unit_price + "元/分,,"
                    + "总价：" + rowData.total_price + "元,,"
                    + "通话次数：" + rowData.total_amount + "次,,"
                    + "计费号码：" + rowData.chargeNumber + ",,"
                    + "是否接收完话单：" + isAccepted + ",,"
                    + "能力类型：" + ability_type + ",,"
                    + "处理状态：" + process_state + ",,"
                    + "异常话单应有数目：" + rowData.tccount + ",,"
                    + "异常话单实际数目：" + rowData.tmicount);// .call_identifier
      });
      // 查看详情
      var numPoolDetail = function(context) {
        var numPool_detail = require("./phonebillexceptiondetail");
        if ($("#phonebillexc_detail_id").length <= 0)
          $("body").append("<div id='phonebillexc_detail_id'></div>");
        numPool_detail.init(
            {
              "title" : "异常话单信息",
              "renderTo" : "phonebillexc_detail_id",
              "details": context
            });

      }
      

      // 重置按钮
      $('#restbtn').click(function() {
        //蒙版
        loader.loading("数据加载中，请稍后……");
        $('#handleState').select2("val", "");
        $('#isvName').select2("val", "");
        $('#applyName').select2("val", "");
        $('#abilityType').select2("val", "");
        $('#callIdentifier').val("");
        daterangeCom.setRangeToToday();
        accountinfo_data_table.fnFilter("");
        return false;
      });
      
      // 导出EXCEL按钮
      $('#btnexport').click(function() {
        // 添加自己的额外参数
        var cond = getCondition();
        $("#export_form").attr("action", "/unusual/exportUnusual.do");
        $("#id_q").val(cond);
        $("#export_form").submit();

        // 此方法不能使用ajax的回传返回结果，因为在service中使用了response的getOutputStream()方法，
        // 该方法执行后就不能继续执行response.getWriter()，否则会报错(在CoreFileter.java中的ajaxMethod方法中报错)。
       /* loader.loading("异常话单导出中，请稍后……");
        //拼接where查询条件
        var cond = getCondition();
        $.ajax(
         {
           url : "/unusual/myExport.do",//exportUnusual,myExport
           dataType : "json",
           data : "q=" + cond,
           type : "POST",
           async : false,
           success : function(json) {
             if (json.flag == '000000') {
               alert("异常话单导出成功！");
               loader.noloading();
             } else if(json.flag == '200000'){
               alert("当前异常话单信息不存在，请选择需要导出异常话单信息！");
               loader.noloading();
             } else {
               oauth2Relogin();
             }
           },
           error : function() {
             loader.noloading();
             bootbox.alertTimeout("网络请求失败，请重试！");
           }
         });*/

        return false;
      });

    });
    
  };
});
